<template>
  <div class="main-content">
    <div class="screen-header">
      <img src="../../screen/img/yth-logo.png">
      <h3>云南数字冷库管理智慧大屏</h3>
      <h2>{{ dateFormat(currentTime) }}</h2>
    </div>

    <div class="wrapper">
      <div class="container-fluid">
        <div class="row fill-h">
          <div class="col-lg-3 fill-h" style="width: 30%">
            <div class="xpanel-wrapper xpanel-wrapper-2">
              <div class="span-title">
                <span>产量统计</span>
              </div>
              <div class="xpanel">
                <div style="height: 100%;width: 100%">
                  <div style="height: 20%;width: 100%">
                    <p style="padding: 20px 0 0 30px;color: #23c9f9;font-size: 20px">年度累计总产量  <span style="padding-left: 5px;color: #ffffff;font-size: 25px">{{ totalNum }}</span></p>
                  </div>
                  <div class="fill-h" id="harvest" style="height: 80%;width: 100%;min-height: 80%"></div>
                </div>
              </div>
            </div>
            <div class="xpanel-wrapper xpanel-wrapper-2">
              <div class="span-title">
                <span>月度工作量对比</span>
              </div>
              <div class="xpanel">
                <div class="fill-h" id="monthWork"></div>
              </div>
            </div>
          </div>
          <div class="col-lg-6 fill-h" style="width: 40%">
            <div class="xpanel-wrapper xpanel-wrapper-2">
              <!--                <video-player ref="videoPlayer" class="video-player vjs-custom-skin" :playsinline="true" :options="playerOptions"-->
              <!--                              @play="onPlayerPlay($event)" @pause="onPlayerPause($event)" />-->
              <VideoView  ref="videoHls" />
            </div>

            <div class="xpanel-wrapper xpanel-wrapper-2">
              <div class="span-title">
                <span>单位对比</span>
              </div>
              <div class="xpanel">
                <div class="fill-h" id="poleLength"></div>
              </div>
            </div>
          </div>
          <div class="col-lg-3 fill-h" style="width: 30%">
            <div class="col-lg-3" style="width: 100%;height: 50%">
              <div class="xpanel-wrapper xpanel-wrapper-3" style="height: 25%;display: flex;">
                <div style="flex:1;margin-left: 90px;">
                  <p style="margin-bottom: 5px;color: #f5f5f5;font-size: 15px;">今日鲜切花</p>
                  <p style="margin-bottom: 5px;color: #ffffff;font-size: 25px;">{{todayFlowerNum}}<img :src="up" class="img_icon"></p>
                </div>
                <div style="flex:1">
                  <p style="margin-bottom: 5px;color: #f5f5f5;font-size: 15px;">昨日鲜切花</p>
                  <p style="margin-bottom: 5px;color: #ffffff;font-size: 25px;">{{yesterdayFlowerNum}}<img :src="down" class="img_icon"></p>
                </div>
              </div>
              <div class="xpanel-wrapper xpanel-wrapper-3" style="height: 75%">
                <div class="span-title">
                  <span>产品分布</span>
                </div>
                <div class="xpanel-1">
                  <div class="fill-h" id="classify"></div>
                </div>
              </div>
            </div>


            <div class="xpanel-wrapper xpanel-wrapper-2">
              <div class="span-title">
                <span>分拣实况</span>
              </div>
              <div class="xpanel">
                <div class="fill-h" style="margin: 20px">
                  <a-table
                    :rowClassName="rowClassName"
                    :scroll="{ y: 200 }"
                    rowKey="packer"
                    :columns="columns"
                    :data-source="data"
                    :pagination="false"
                    :loading="loading"
                    :bordered="false"
                  >
                  </a-table>
                  <!--                    style="min-height: 300px"-->

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>


<script>
import $ from 'jquery'
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
import "../../screen/css/app.css";
import 'videojs-contrib-hls'
import VideoView from './VideoView'
import { queryTableList, getPoleLengthData, getMonthWorkData, getCurrentSortFlower, queryPoleLevelYear, queryPoleLevelMonth, ajaxGetDictItems, queryVariety } from '@/api/api'
export default {
  components: { VideoView },
  data() {
    return {
      todayFlowerNum: 0,
      yesterdayFlowerNum: 0,
      up: require('@/screen/img/up.png'),
      down: require('@/screen/img/down.png'),
      symbolImgHead: require('@/screen/img/rose1.png'),
      symbolImg: require('@/screen/img/pole.png'),
      productCharts: null,
      poleLevelYearData: [],
      poleLevelMonthData: [],
      classifyCharts: null,
      classifyData: [],
      monthWorkCharts: null,
      monthWorkData: [],
      poleLengthCharts: null,
      poleLengthData: [],
      yearProduct: 0, //年度产量总数
      monthProduct: 0, //月度产量总数
      windowHeight: document.documentElement.clientHeight,   //实时屏幕高度
      changeHeight: 0,
      loading: false,
      totalNum: 0,
      timer: null,
      currentTime: new Date(),
      isFullscreen: false,
      srcvideo: '', //视频地址,
      data: [],
      columns: [
        {
          title: '排名',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'分拣员',
          align:"center",
          dataIndex: 'packer'
        },
        {
          title:'分拣量(枝)',
          align:"center",
          dataIndex: 'total'
        },
        {
          title:'实时贡献(%)',
          align:"center",
          dataIndex: 'per'
        }
      ],
      // 分页参数
      pagination: {
        current: 1,
        pageSize: 8,
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    };
  },
  computed: {

  },
  watch: {

  },
  created() {

  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  mounted() {
    this.getVideoUrl()
    let that = this
    this.timer = setInterval(function () {
      that.currentTime = new Date().toLocaleString()
    })
    this.judgeCount()
    // 需要在页面DOM加载完成后加载图表
    this.initEcharts()
    this.queryData()

    /* 窗口变化时自适应 步骤一:监听窗口变化 */
    window.addEventListener('resize', this.resizeHandle)

    let dom = document.querySelector('.ant-table-body')

    // 监听屏幕高度
    window.onresize = () => {
      return (() => {
        window.screenHeight = document.body.clientHeight;
        this.changeHeight = window.screenHeight;
        if (this.windowHeight < this.changeHeight) {
          console.log(dom.style.height)
          dom.style.height = "260px"
          console.log(dom.style.height)
        } else {
          console.log(dom.style.height)
          dom.style.height = "200px"
          console.log(dom.style.height)
        }
      })();

    };

    // 表格滚动的节点class dom.scrollTop 当前节点滚动条距离顶部的距离为0就在顶部 dom.scrollHeight 当前滚动内容得高度
    // dom.clientHeight 当前节点可视窗口的高度  this.$refs.menuItem.style.color='blue';
    console.log(this.windowHeight)
    console.log(dom.addEventListener, dom.scrollHeight, dom.scrollTop, dom.clientHeight)
    dom.addEventListener('scroll', function () {
      // scrollDistance 为零时滚动到底部
      const scrollDistance = dom.scrollHeight - dom.scrollTop - dom.clientHeight
      // console.log(scrollDistance, '------', dom.scrollHeight, dom.scrollTop, dom.clientHeight)
      if (scrollDistance <= 0) { // 等于0证明已经到底，可以请求接口
        that.queryData()
        console.log(that.pagination.current)
      }
    })

  },
  destroyed () {
    /* 窗口变化时自适应 步骤三 组件被注销时，缩放函数是匿名函数，且仍然在事件监听列表中，
    因此匿名函数和匿名函数中用到的外部变量在组件注销后均不会被清理。
     所以要手动清理 */
    window.removeEventListener('resize', this.resizeHandle)
  },
  methods: {
    judgeCount() {
      getCurrentSortFlower().then((res)=>{
        if(res.success){
          this.totalNum = res.result.total
          this.todayFlowerNum = res.result.today
          this.yesterdayFlowerNum = res.result.yesterday
          let before_yes = res.result.before_yesterday
          if (this.todayFlowerNum > this.yesterdayFlowerNum) {
            this.up=require('@/screen/img/up.png')
          } else {
            this.up=require('@/screen/img/down.png')
          }
          if (this.yesterdayFlowerNum > before_yes) {
            this.down=require('@/screen/img/up.png')
          } else {
            this.down=require('@/screen/img/down.png')
          }
        }
      })
    },
    getVideoUrl() {
      const dictCode = 'planting_flower_video'
      ajaxGetDictItems(dictCode, null).then((res) => {
        if (res.success && res.result.length > 0) {
          this.srcvideo = res.result[0].text;
          let videoView = this.$refs.videoHls
          videoView.initVideo(this.srcvideo)
        }
      })

    },
    queryPoleLevelYear() {
      return new Promise((resolve, reject)=>{
        queryPoleLevelYear().then((res)=>{
          if(res.success){
            this.poleLevelYearData = res.result;
            resolve()
          }
        })
      })
    },
    queryPoleLevelMonth() {
      return new Promise((resolve, reject)=>{
        queryPoleLevelMonth().then((res)=>{
          if(res.success){
            this.poleLevelMonthData = res.result;
            resolve()
          }
        })
      })
    },
    queryVariety() {
      return new Promise((resolve, reject)=>{
        queryVariety().then((res)=>{
          if(res.success){
            this.classifyData = res.result;
            resolve()
          }
        })
      })
    },
    getMonthWork() {
      return new Promise((resolve, reject)=>{
        getMonthWorkData().then((res)=>{
          if(res.success){
            this.monthWorkData = res.result;
            resolve()
          }
        })
      })
    },
    getPoleLength() {
      return new Promise((resolve, reject)=>{
        getPoleLengthData().then((res)=>{
          if(res.success){
            // this.data = res.result.records;
            this.poleLengthData = res.result;
            resolve()
          }
        })
      })
    },
    resizeHandle() {
      if (this.productCharts !== null) {
        this.productCharts.resize()
      }
      if (this.classifyCharts !== null) {
        this.classifyCharts.resize()
      }
      if (this.monthWorkCharts !== null) {
        this.monthWorkCharts.resize()
      }
      if (this.poleLengthCharts !== null) {
        this.poleLengthCharts.resize()
      }
    },
    initEcharts() {
      this.initProduct()
      this.initClassify()
      this.initMonthWork()
      this.initPoleLength()
    },
    rowClassName (record, index){
      let className = index % 2 ? 'shallow_gray': 'deep_gray';
      return className
    },
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;

    },
    queryData() {
      let params = {}
      params.pageNo = this.pagination.current;
      params.pageSize = this.pagination.pageSize;
      let that = this
      queryTableList(params).then((res)=>{
        if(res.success){
          // this.data = res.result.records;
          if (res.result.records.length !== 0) {
            that.pagination.current ++
            that.data = that.data.concat(res.result.records)
            console.log(that.data)
            this.pagination.total = res.result.total;
          }
        }
      })
    },
    async initProduct() {
      let legendData = []
      await this.queryPoleLevelYear()
      let yearData = []
      for (let key in this.poleLevelYearData) {
        const data = {value: 0,name: ''}
        data.value = this.poleLevelYearData[key]
        data.name = key
        yearData.push(data)
        legendData.push(key)
      }

      await this.queryPoleLevelMonth()

      let currentYear = (new Date()).getFullYear()
      let currentMonth = (new Date()).getMonth() + 1
      let monthData = []
      for (let key in this.poleLevelMonthData) {
        const data = {value: 0,name: ''}
        data.value = this.poleLevelMonthData[key]
        data.name = key
        monthData.push(data)
      }
      // 基于准备好的dom，初始化echarts实例
      this.productCharts = this.$echarts.init(document.getElementById('harvest'))

      this.productCharts.setOption({
        title: [
          {
            subtext: '年度产量',
            left: '24%',
            top: '10%',
            textAlign: 'center',
            subtextStyle: {
              fontSize: 13,
              color: '#fff'
            }
          },
          {
            subtext: '月度产量',
            left: '74%',
            top: '10%',
            textAlign: 'center',
            subtextStyle: {
              fontSize: 13,
              color: '#fff'
            }
          },
        ],

        // graphic: [
        //   {
        //     type: "text",
        //     left: '24%',
        //     top: "center",
        //     style: {
        //       text:
        //         "总量" +  //圆饼中心显示数据，这里是显示得总数
        //         "\n" + this.yearProduct,
        //       textAlign: "center",
        //       fill: "#ffffff",
        //       width: 30,
        //       height: 30,
        //       fontSize: 12
        //     }
        //   },
        //   {
        //     type: "text",
        //     left: '74%',
        //     top: "center",
        //     style: {
        //       text:
        //         "总量" +  //圆饼中心显示数据，这里是显示得总数
        //         "\n" + this.monthProduct,
        //       textAlign: "center",
        //       fill: "#ffffff",
        //       width: 30,
        //       height: 30,
        //       fontSize: 12
        //     }
        //   }
        // ],
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: '-1%',
          top: 'bottom',
          data: legendData,
          textStyle: {
            fontSize: 10,
            color: '#fff'
          }
        },
        toolbox: {
          show: false,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        series: [
          {
            name: currentYear + '年 年度产量',
            type: 'pie',
            radius: [60, 75],
            center: ['25%', '55%'],
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            data: yearData
          },
          {
            name: currentMonth + '月 月度产量',
            type: 'pie',
            radius: [60, 75],
            center: ['75%', '55%'],
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            data: monthData
          }
        ]
      })
    },
    async initClassify() {
      await this.queryVariety()
      let xAxisData = []
      let AA_DATA = []
      let A_DATA = []
      let B_DATA = []
      let C_DATA = []
      let D_DATA = []
      let E_DATA = []
      for (let key in this.classifyData) {
        xAxisData.push(this.classifyData[key].variety)
        AA_DATA.push(this.classifyData[key].AA)
        A_DATA.push(this.classifyData[key].A)
        B_DATA.push(this.classifyData[key].B)
        C_DATA.push(this.classifyData[key].C)
        D_DATA.push(this.classifyData[key].D)
        E_DATA.push(this.classifyData[key].E)
      }
      // 基于准备好的dom，初始化echarts实例
      this.classifyCharts = this.$echarts.init(document.getElementById('classify'))

      this.classifyCharts.setOption({
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          left: '-7px',
          top: '7%',
          data: ['等级AA', '等级A', '等级B', '等级C', '等级D', '等级E'],
          textStyle: {
            fontSize: 10,
            color: '#fff'
          }
        },
        grid: {
          top: 55,
          left: 35,
          right: 35,
          bottom: 35,
          width:'auto',
          height:'auto'
        },
        toolbox: {
          show: false,
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            textStyle: {
              color: '#ffffff',
            },
          },
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          scale:true,
          splitLine: {
            show: true,
            lineStyle: {
              color: "#235080"
            }
          }
        },
        series: [
          {
            name: '等级AA',
            type: 'line',
            stack: 'Total',
            data: AA_DATA
          },
          {
            name: '等级A',
            type: 'line',
            stack: 'Total',
            data: A_DATA
          },
          {
            name: '等级B',
            type: 'line',
            stack: 'Total',
            data: B_DATA
          },
          {
            name: '等级C',
            type: 'line',
            stack: 'Total',
            data: C_DATA
          },
          {
            name: '等级D',
            type: 'line',
            stack: 'Total',
            data: D_DATA
          },
          {
            name: '等级E',
            type: 'line',
            stack: 'Total',
            data: E_DATA
          }
        ]
      })
    },
    async initMonthWork() {
      // 请求图表数据
      await this.getMonthWork()
      // 基于准备好的dom，初始化echarts实例
      this.monthWorkCharts = this.$echarts.init(document.getElementById('monthWork'))
      let dataAxis = ['在用', '待修', '在修', '备用', '调剂', '闲置', '待报废', '报废', '丢失', '归档', '其他'];
      let data = []
      for (let key in this.monthWorkData) {
        data.push(this.monthWorkData[key].total)
      }

      this.monthWorkCharts.setOption( {
        xAxis: {
          type: 'category',
          axisLabel: {
            textStyle: {
              color: '#ffffff',
            },
          },
          data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
        },
        yAxis: {
          type: 'value',
          scale:true,
          splitLine: {
            show: true,
            lineStyle: {
              color: "#235080"
            }
          }
        },
        grid: {
          top: 35,
          left: 55,
          right: 45,
          bottom: 35,
          width:'auto',
          height:'auto'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        series: [
          {
            data: data,
            type: 'line',
            label: {
              normal: {
                show: true,
                position: 'top',
                fontStyle: "normal",
                color: "#8feeff"
              }
            },
            itemStyle: {
              color: "#4CC5F6"
            },
            smooth: true
          }
        ]
      })
    },
    initPoleLength: async function() {
      await this.getPoleLength()
      let data = [
        {
          type: 'pictorialBar',
          symbol: 'image://' + this.symbolImgHead,
          z: 10,
          data: [],
          label: {
            normal: {
              show: true,
              position: 'top',
              fontStyle: 'normal',
              color: '#8feeff'
            }
          }
        },
        {
          type: 'pictorialBar',
          symbol: 'image://' + this.symbolImg,
          z: 9,
          data: [],
          label: {
            normal: {
              show: false,
              position: 'top',
              fontStyle: 'normal',
              color: '#8feeff'
            }
          }
        },
        {
          data: [],
          type: 'line',
          itemStyle: {
            color: "#4CC5F6"
          },
          smooth: true
        }
      ]

      for (let key in this.poleLengthData) {
        let data1 = {
          value: 0,
          symbolPosition: 'end',
          symbolSize: [
            '100%', 30
          ]
        }
        let data2 = {
          value: 0,
          symbolPosition: 'start',
          symbolSize: [
            '100%', '90%'
          ]
        }
        data1.value = this.poleLengthData[key].total
        data[0].data.push(data1)
        data2.value = this.poleLengthData[key].total
        data[1].data.push(data2)
        data[2].data.push(this.poleLengthData[key].total)
      }
      var rocket =
        'path://M-244.396,44.399c0,0,0.47-2.931-2.427-6.512c2.819-8.221,3.21-15.709,3.21-15.709s5.795,1.383,5.795,7.325C-237.818,39.679-244.396,44.399-244.396,44.399z M-260.371,40.827c0,0-3.881-12.946-3.881-18.319c0-2.416,0.262-4.566,0.669-6.517h17.684c0.411,1.952,0.675,4.104,0.675,6.519c0,5.291-3.87,18.317-3.87,18.317H-260.371z M-254.745,18.951c-1.99,0-3.603,1.676-3.603,3.744c0,2.068,1.612,3.744,3.603,3.744c1.988,0,3.602-1.676,3.602-3.744S-252.757,18.951-254.745,18.951z M-255.521,2.228v-5.098h1.402v4.969c1.603,1.213,5.941,5.069,7.901,12.5h-17.05C-261.373,7.373-257.245,3.558-255.521,2.228zM-265.07,44.399c0,0-6.577-4.721-6.577-14.896c0-5.942,5.794-7.325,5.794-7.325s0.393,7.488,3.211,15.708C-265.539,41.469-265.07,44.399-265.07,44.399z M-252.36,45.15l-1.176-1.22L-254.789,48l-1.487-4.069l-1.019,2.116l-1.488-3.826h8.067L-252.36,45.15z'

      // 基于准备好的dom，初始化echarts实例
      this.poleLengthCharts = this.$echarts.init(document.getElementById('poleLength'))
      this.poleLengthCharts.setOption({
        color: '#bb0004',
        xAxis: {
          type: 'category',
          data: ['35', '40', '45', '50', '55', '60', '65', '70', '75', '80', '85'],
          axisLabel: {
            textStyle: {
              color: '#ffffff'
            }
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: true,
            lineStyle: {
              color: '#235080'
            }
          }
        },
        grid: {
          top: 35,
          left: 45,
          right: 0,
          bottom: 35,
          width: 'auto',
          height: 'auto'
        },
        tooltip: {
          trigger: 'item',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#438523'
            }
          }
        },
        series: data
      })
    },
    // 时间格式化
    dateFormat () {
      var date = new Date()
      var year = date.getFullYear()

      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      let week = date.getDay() // 星期
      let weekArr = [ '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六' ]
      // 拼接 时间格式处理
      return year + '年' + month + '月' + day + '日 ' + hours + ':' + minutes + ':' + seconds
    }

  },
};
</script>

<style scoped>
::v-deep  .ant-table-body {
  max-height: 260px !important;
  height: 200px;
  background: #034473;
}
::v-deep .ant-table-fixed-header > .ant-table-content > .ant-table-scroll > .ant-table-body {
  background: #034473;
}
::v-deep .ant-table-placeholder {
  display: none;
}
::v-deep .ant-table-header {
  border-radius: 6px;
}
::v-deep .ant-table-thead > tr > th, ::v-deep .ant-table-tbody > tr > td {
  padding: 6px 6px;
  word-break: break-word;
}
::v-deep .ant-table-pagination.ant-pagination {
  margin: 2px 0;
}
::v-deep .shallow_gray {
  background-color: #0462A8;
}
::v-deep .deep_gray {
  background-color: #073D7A;
}
::v-deep .ant-table-thead {
  background: #3071b9 ;
}
/*在鼠标悬浮时背景色展示在当前项非当前行*/
::v-deep  .ant-table-tbody > tr > td {
  background: rgba(255,255,255,0) !important;
}
::v-deep .ant-table-tbody > tr >td:hover{
  background: rgb(255,255,255) !important;
}
/*去除鼠标悬浮的背景色*/
::v-deep  .ant-table-tbody > tr > td {
  background: rgba(255,255,255,0) !important;
}
::v-deep .ant-table-tbody > tr >td:hover{
  background: rgba(255,255,255,0) !important;
}

/*去除边框颜色*/
::v-deep .ant-table-tbody > tr > td {
  border-bottom: 0 solid #e8e8e8;
  transition: background 0.3s;
}
::v-deep .ant-table-thead > tr > th {
  border-bottom: 0 solid #e8e8e8;
}
::v-deep .ant-table-thead > tr >th{
  color: white;
  background: #0462A8 !important;
}
/*//修改列表文字、背景颜色*/
::v-deep .ant-table-tbody > tr >td{
  color: white !important;
}
</style>